<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2018/12/12
 * Time: 10:31
 */

namespace app\admin\service;


use app\admin\model\Product;
use Driver\Cache\Redis;
use Page\Page;

class ProductService
{
    private $model;
    public function __construct()
    {
        $this->model = new Product();
    }

    /**
     * @param $post_data 添加客户端from表单传过来的所有数据
     * @return Product
     */
    public function addProduct($post_data)
    {
        $post = unsetArrNull($post_data);
        $post['add_time'] = now_time();
        $result =  $this->model->create($post);
        # 获取添加id值
        $id = $result->id;
        # 同步更新redis_set里面id集合
        $this->add_id_to_set($id, $post['status']);
        return $result;
    }
    /**
     * 更新客户端from表单传过来的所有数据
     * 同步redis-hash里面商品详情的更新
     * @param $post_data
     * @return Product
     */
    public function upProduct($post_data)
    {
        $post = unsetArrNull($post_data);
        $newArr = $this->getCheckStatus($post);
        $product_id = $newArr['product_id'];
        unset($newArr['product_id']);
        $newArr['up_time'] = now_time();
        $result = $this->model->where('product_id','=',$product_id)
            ->update($newArr);
        # 同步redis-hash商品详情的更新
        $this->UpProductInRedis($product_id,$newArr);
        # 同步更新redis_set里面id集合
        $this->add_id_to_set($post['product_id'], $post['status']);
        return $result;
     }

    /**
     * 产品查询接口
     * @param $post
     * @return array
     */
     public function FindConditionByProduct($post)
     {
         $arr = $this->SpliceWhereArr($post);
         $page = new Page($this->model,$arr['page'],$arr['limit'],[],[],$arr['where']);
         $result = $page->layuiPage();
         return $result;
     }

    /**
     * 定义一个数组用于存单选框的状态
     * 再和客户端from表单post提交的数组合并
     * @param $post_data
     * @return array
     */
    private function getCheckStatus($post_data)
    {
        $check = [
            'repeat' => 0,
            'pay_zfb' => 0,
            'pay_wx' => 0,
            'pay_app' => 0,
            'pay_BankCard' => 0,
            'pay_web' => 0,
            'pay_Money' => 0
        ];
        $newArr = array_merge($check,$post_data);
        return $newArr;
    }
    private function UpProductInRedis($product_id,$data)
    {
        $key = config('redis.product').$product_id;
        $redis_key = Redis::FindKeys($key);
        if(!$redis_key){
            return ;
        }
        $result = Redis::hMset($key,$data);
        if($result !== 1){
            Redis::DelKey($key);
        }
        return ;
    }

    /**
     * 组装where插叙条件
     * @param $post 客户端传过来的值
     * @return array
     */
    private function SpliceWhereArr($post)
    {
        $page = $post['page'];
        $limit = $post['limit'];

        $filed = $post['field'];
        $time = $filed['time'];
        if(!strstr($time,'.')){
            $time_start = '';
            $time_end = '';
        }else {
            $date = explode('.', $filed['time']);
            $time_start = $date[0];
            $time_end = $date[1];
        }

        $arr = [
            'status' => $filed['status'] == '' ? ['status','<>',null] : ['status','=',$filed['status']],
            'grade' => ['grade','=',$filed['grade']],
            'category_id' => ['category_id','=',$filed['category_id']],
            'title' => ['title','like','%'.$filed['title'].'%'],
            'time' => ['add_time', 'between time', [$time_start, $time_end]]
        ];
        # 组装where查询条件数组
        $where = [];
        foreach ($filed as $key => $value){
            if($value == ''){
                unset($arr[$key]);
                continue;
            }
            array_push($where,$arr[$key]);
        }

        return [
          'page' => $page,
          'limit' => $limit,
          'where' => $where
        ];
    }

    # 在redis_set中添加或者删除产品id，
    private function add_id_to_set($id, $status)
    {
        $redis_set_key = config('redis.ids');
        if($status == 1){
            Redis::sAdd($redis_set_key, $id);
        }else{
            Redis::sRm($redis_set_key, $id);
        }
    }

    # 查询px最大值还有每个分类的个数
    public function grade_info()
    {
        $first = 0;
        $secord = 0;
        $third = 0;

        $model = new Product();
        $lists = $model->where('status', '=', 1)
            ->order('px','desc')
            ->select()
            ->toArray();
        foreach ($lists as $list){
            if($list['grade'] == 'A'){
                $first ++;
            }
            if($list['grade'] == 'B'){
                $secord ++;
            }
            if($list['grade'] == 'C'){
                $third ++;
            }
        }
        return [
            'px' => $lists[0]['px'],
            'first' => $first,
            'secord' => $secord,
            'third' =>$third
        ];
    }
}